let allData = [];
// 初始化成绩列表数据
const init = async () => {
  // 获取成绩数据
  let response = await fetch(`./mock/data.json`);
  let data = await response.json();
  allData = data;
  // 页面需要显示的数据
  renderTable(data);
};
init();

let HighLight = null; // 用来高亮显示各个筛选出来的数据
// 所有条件渲染下拉框
const allConditions = [
  { value: "", label: "请选择所有" },
  { value: "缺考", label: "全部科目缺考" },
  { value: "0", label: "全部科目 0 分" },
  { value: "full", label: "全部科目满分" },
  { value: "failedFew", label: "一科以上未及格（包含一科）" },
];

// 初始化 select 下拉菜单
function renderOptions(el, options) {
  const select = document.getElementById(el);
  options.forEach((option) => {
    const optionEl = document.createElement("option");
    optionEl.value = option.value;
    optionEl.textContent = option.label;
    select.appendChild(optionEl);
  });
}
renderOptions("allConditions", allConditions);

// 下拉框，所有条件
function allConditionsSelect() {
  HighLight = false;
  const selectedOption = document.getElementById("allConditions").value;
  console.log(`全部查询: ${selectedOption}`);
  if (selectedOption == "") {
    init();
  }
  // 如果查询全部满分
  let filteredData2;
  if (selectedOption == "full") {
    filteredData2 = queryScoreList(allData, { perfectScore: true });
  } else if (selectedOption == "failedFew") {
    HighLight = true;
    // 未及格成绩 1 门以上
    filteredData2 = queryScoreList(allData, {
      failedFew: true,
    });
  } else {
    // 查询全部为某个值的数据
    filteredData2 = queryScoreList(allData, {
      score: selectedOption,
      matchAll: true,
    });
  }
  renderTable(filteredData2);
}
// 准考证查询
const searchData = () => {
  HighLight = true;
  let admissionTicketVal = document.getElementById("admission-ticket").value;
  let filteredData = queryScoreList(allData, {
    students: admissionTicketVal.replace(/\s+/g, ""),
  }); // 根据学生查询数据，学生可以是多个，以逗号分割
  renderTable(filteredData);
};
// 根据成绩数据渲染表格
function renderTable(data) {
  let tableData = data.map((student) => {
    const [id, scores] = Object.entries(student)[0];
    const scoreObj = scores.reduce((result, score) => {
      const [num, value] = Object.entries(score)[0];
      result[num] = value;
      return result;
    }, {});
    return { id, ...scoreObj };
  });

  const scoreList = document.getElementById("scoreList");
  scoreList.innerHTML = "";
  tableData.forEach((data) => {
    const tr = document.createElement("tr");
    scoreList.appendChild(tr);
    const td2 = document.createElement("td");
    td2.textContent = data.id;
    tr.appendChild(td2);
    for (let i = 1; i < 7; i++) {
      const cell = document.createElement("td");
      const value = data[i];
      const isHighlight =
        HighLight && ((i < 5 && value < 60) || (i > 4 && value < 90));
      cell.className = isHighlight ? "highlight" : "";
      cell.textContent = value;
      tr.appendChild(cell);
    }
  });
}